import { observable, action, toJS, computed } from 'mobx';
import BaseWithList from 'stores/models/core/list';
import Event from 'stores/models/core/nodeWithList/base/event';
import { loadModulesModel, findSimulator } from 'common/utils/store';

/**
 * NodeWithList
 */
export default class NodeWithList extends BaseWithList {
  node = null;

  // 是否可见
  @observable visible = true;

  // 是否锁定
  @observable lock = false;

  // 事件列表
  @observable events = [];

  // 返回元素的真实矩形尺寸等数据 - （left / top 相对于整个文档）
  @computed get rect() {
    const simulator = findSimulator(this);
    const { scale } = simulator;
    const left = (this.left || 0) * scale + simulator.left;
    const top = (this.top || 0) * scale + simulator.top;
    const width = (this.width || 1) * scale;
    const height = (this.height || 1) * scale;
    return {
      left,
      top,
      right: left + width,
      bottom: top + height,
      width,
      height,
    };
  }

  /**
   * 新建模块
   * @param item
   * @param fromIndex
   */
  @action async addModule(item = {type: ''}, fromIndex = -1) {
    // item {type: "image", label: "图片"}
    // console.log(item.list); // undefined
    const list = toJS(item.list);
    item.list = [];
    const Model = await loadModulesModel(item.type);
    const module = new Model(item);
    // console.log('module:', module);
    this.insert(module, fromIndex);
    if (list && list.length) {
      list.map( itemX => {
        module.addModule(itemX);
      });
    }
  }

  /**
   * 复制模块
   * @param item
   * @param fromIndex
   * @returns {Promise.<void>}
   */
  @action async copyModule(item, fromIndex = -1) {
    let copyItem = toJS(item);
    copyItem.parent = this;
    copyItem.current = null;
    this.addModule(copyItem, fromIndex);
  }

  /**
   * 关联node
   * @param ref
   */
  @action setNode(ref) {
    this.node = ref;
  }


  /**
   * 添加事件
   */
  @action addEvent(data) {
    const event = new Event(data);
    this.events.push(event);
  }

  /**
   * 删除事件
   */
  @action removeEvent(event) {
    this.events.remove(event);
  }
}
